﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Jayden.Dll.Cards.Enums;

namespace Jayden.Dll.Cards.Drawing
{
	public class CardImage
	{
		private bool m_FourColorDeck = true;
		private bool m_HasJoker = true;
		private int m_BackImages = 4;
		private Image m_Images;
		private Image[] m_Image = new Image[14 * 6];

		private Size m_CardSize;

		public CardImage(string filename, bool fourColor = true, bool joker = true, int backImages = 4)
		{
			m_Images = Image.FromFile(filename);
			m_FourColorDeck = fourColor;
			m_HasJoker = joker;
			m_BackImages = backImages;

			m_CardSize = new Size(m_Images.Width / 14, m_Images.Height / 6);
		}

		public int Width { get { return m_CardSize.Width; } }
		public int Height { get { return m_CardSize.Height; } }

		public Image GetImage(int x, int y)
		{
			int index = x + y * 14;
			Image image = m_Image[index];
			if (image == null)
			{
				image = new Bitmap(m_CardSize.Width, m_CardSize.Height);
				using (Graphics g = Graphics.FromImage(image))
				{
					g.DrawImage(m_Images, 0, 0, new Rectangle(x * m_CardSize.Width, y * m_CardSize.Height, m_CardSize.Width, m_CardSize.Height), GraphicsUnit.Pixel);
				}
				m_Image[index] = image;
			}
			return image;
		}

		public int GetX(CardRank rank)
		{
			switch (rank)
			{
				case CardRank.Two:
					return 12;
				case CardRank.Three:
					return 11;
				case CardRank.Four:
					return 10;
				case CardRank.Five:
					return 9;
				case CardRank.Six:
					return 8;
				case CardRank.Seven:
					return 7;
				case CardRank.Eight:
					return 6;
				case CardRank.Nine:
					return 5;
				case CardRank.Ten:
					return 4;
				case CardRank.Jack:
					return 3;
				case CardRank.Queen:
					return 2;
				case CardRank.King:
					return 1;
				case CardRank.Ace:
					return 0;
			}
			throw new Exception("Unknow rank.");
		}
		public int GetY(CardSuit suit, bool fourColor)
		{
			fourColor &= m_FourColorDeck;
			switch (suit)
			{
				case CardSuit.Hearts:
					return 1;
				case CardSuit.Diamonds:
					return fourColor ? 4 : 2;
				case CardSuit.Clubs:
					return fourColor ? 5 : 3;
				case CardSuit.Spades:
					return 0;
			}
			throw new Exception("Unknow suit.");
		}

		public Image GetCard(Card card, bool fourColor)
		{
			return GetImage(GetX(card.Rank), GetY(card.Suit, fourColor));
		}
		public Image GetBack(int index)
		{
			index = Math.Max(0, Math.Min(m_BackImages, index));
			return GetImage(13, index);
		}
		public Image Joker { get { return GetImage(13, 4); } }
	}
}
